package com.ruoyi.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.domain.Article;
import com.ruoyi.mapper.RiverNewsMapper;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.RiverNews;
import com.ruoyi.service.IRiverNewsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * river_newsController
 * 
 * @author ya
 * @date 2025-06-22
 */
@RestController
@RequestMapping("/river_news/river_news")
public class
RiverNewsController extends BaseController
{
    @Autowired
    private IRiverNewsService riverNewsService;

    @Autowired
    private FileStorageService fileStorageService;//注入实列
    @Autowired
    private RiverNewsMapper riverNewsMapper;


    /**
     * 封面路径
     */
    @Anonymous
    @PostMapping("/filePath/{id}")
    public AjaxResult uploadFile(@PathVariable Long id, @RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "articleFilePath/filePath/"; // 直接在这里设置基础路径，或者从配置文件中读取

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 创建Article对象并设置ID和filePath
            RiverNews riverNews = new RiverNews();
            riverNews.setNewsId(id);
            riverNews.setCoverPath(fileInfo.getUrl());
            System.out.printf("封面路径："+fileInfo.getUrl());

            // 更新数据库中的filePath字段
            riverNewsMapper.updateRiverNewsOwn(riverNews);

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询river_news列表
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('river_news:river_news:list')")
    @GetMapping("/list")
    public TableDataInfo list(RiverNews riverNews)
    {
        startPage();
        List<RiverNews> list = riverNewsService.selectRiverNewsList(riverNews);
        return getDataTable(list);
    }

    /**
     * 查询未下架且最新日期的8条河道要闻，供网站前端使用
     */
    @Anonymous
    @GetMapping("/latest8")
    public AjaxResult getLatest8RiverNews() {
        List<RiverNews> list = riverNewsService.selectLatest8RiverNews();
        return success(list);
    }

    /**
     * 导出river_news列表
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:export')")
    @Log(title = "river_news", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RiverNews riverNews)
    {
        List<RiverNews> list = riverNewsService.selectRiverNewsList(riverNews);
        ExcelUtil<RiverNews> util = new ExcelUtil<RiverNews>(RiverNews.class);
        util.exportExcel(response, list, "river_news数据");
    }

    /**
     * 获取river_news详细信息
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:query')")
    @GetMapping(value = "/{newsId}")
    public AjaxResult getInfo(@PathVariable("newsId") Long newsId)
    {
        return success(riverNewsService.selectRiverNewsByNewsId(newsId));
    }

    /**
     * 新增river_news
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:add')")
    @Log(title = "river_news", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RiverNews riverNews)
    {
        return toAjax(riverNewsService.insertRiverNews(riverNews));
    }

    /**
     * 修改river_news
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "river_news", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RiverNews riverNews)
    {
        return toAjax(riverNewsService.updateRiverNews(riverNews));
    }

    /**
     * 自己新增river_news
     */
    //PreAuthorize("@ss.hasPermi('river_news:river_news:add')")
    @Log(title = "river_news", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestParam(value="title",required = false) String title,
                          @RequestParam(value = "articleOrigin",required = false) String articleOrigin,
                          @RequestParam(value = "coverPath",required = false) MultipartFile coverPath,
                          @RequestParam(value ="columnId",required = false) Long columnId,
                          @RequestParam(value = "content",required = false) String content,
                          @RequestParam(value = "author",required = false) String author,
                          @RequestParam(value = "remark",required = false) String remark,
                          @RequestParam(value = "littleTitle1",required = false) String littleTitle1,
                          @RequestParam(value = "littleTitle2",required = false) String littleTitle2,
                          @RequestParam(value = "pubdate",required = false) String pubdate
                          )
    {
        RiverNews riverNews = new RiverNews();
        riverNews.setTitle(title);
        riverNews.setArticleOrigin(articleOrigin);
        riverNews.setColumnId(columnId);
        riverNews.setContent(content);
        riverNews.setAuthor(author);
        riverNews.setRemark(remark);
        riverNews.setLittleTitle1(littleTitle1);
        riverNews.setLittleTitle2(littleTitle2);
        riverNews.setPubdate(pubdate);
        // 处理文件上传
        if (coverPath != null && !coverPath.isEmpty()) {
            String basePath = "articleFilePath/";
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                    + "/" + coverPath.getOriginalFilename();

            FileInfo fileInfo = fileStorageService.of(coverPath)
                    .setPath(objectName)
                    .upload();
            riverNews.setCoverPath(fileInfo.getUrl());
        }
        return toAjax(riverNewsService.insertRiverNewsOwn(riverNews));
    }

    /**
     * 自己修改river_news
     */
    //@PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "river_news", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@RequestParam("newsId") Long newsId, @RequestParam(value="title",required = false) String title,
                           @RequestParam(value = "articleOrigin",required = false) String articleOrigin,
                           @RequestParam(value = "coverPath",required = false) MultipartFile coverPath,
                           @RequestParam(value ="columnId",required = false) Long columnId,
                           @RequestParam(value = "content",required = false) String content,
                           @RequestParam(value = "author",required = false) String author,
                           @RequestParam(value = "remark",required = false) String remark,
                           @RequestParam(value = "littleTitle1",required = false) String littleTitle1,
                           @RequestParam(value = "littleTitle2",required = false) String littleTitle2,
                           @RequestParam(value = "pubdate",required = false) String pubdate
                           )
    {
        RiverNews riverNews = new RiverNews();
        riverNews.setNewsId(newsId);
        riverNews.setTitle(title);
        riverNews.setArticleOrigin(articleOrigin);
        riverNews.setColumnId(columnId);
        riverNews.setContent(content);
        riverNews.setAuthor(author);
        riverNews.setRemark(remark);
        riverNews.setLittleTitle1(littleTitle1);
        riverNews.setLittleTitle2(littleTitle2);
        riverNews.setPubdate(pubdate);
        System.out.println("副标题1："+riverNews.getLittleTitle1());
        System.out.println("副标题2："+riverNews.getLittleTitle2());
        // 处理文件上传
        if (coverPath != null && !coverPath.isEmpty()) {
            String basePath = "articleFilePath/";
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                    + "/" + coverPath.getOriginalFilename();

            FileInfo fileInfo = fileStorageService.of(coverPath)
                    .setPath(objectName)
                    .upload();
            riverNews.setCoverPath(fileInfo.getUrl());
        }
        return toAjax(riverNewsService.updateRiverNewsOwn(riverNews));
    }

    /**
     * 删除river_news
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:remove')")
    @Log(title = "river_news", businessType = BusinessType.DELETE)
	@DeleteMapping("/{newsIds}")
    public AjaxResult remove(@PathVariable Long[] newsIds)
    {
        return toAjax(riverNewsService.deleteRiverNewsByNewsIds(newsIds));
    }
    
    /**
     * 隐藏河道要闻
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "河道要闻", businessType = BusinessType.UPDATE)
    @PutMapping("/hide/{newsId}")
    public AjaxResult hide(@PathVariable Long newsId)
    {
        return toAjax(riverNewsService.offShelfRiverNewsByNewsId(newsId));
    }
    
    /**
     * 显示河道要闻
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "河道要闻", businessType = BusinessType.UPDATE)
    @PutMapping("/show/{newsId}")
    public AjaxResult show(@PathVariable Long newsId)
    {
        return toAjax(riverNewsService.onShelfRiverNewsByNewsId(newsId));
    }
    
    /**
     * 将指定记录上移一位
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "河道要闻", businessType = BusinessType.UPDATE)
    @PutMapping("/moveUp/{newsId}")
    public AjaxResult moveUp(@PathVariable Long newsId) {
        // 获取记录
        RiverNews targetRiverNews = riverNewsService.selectRiverNewsByNewsId(newsId);
        
        if (targetRiverNews == null) {
            return AjaxResult.error("记录不存在");
        }
        
        // 如果sortOrder为null，初始化为最大值+1
        if (targetRiverNews.getSortOrder() == null) {
            int maxSortOrder = riverNewsService.selectMaxSortOrder();
            targetRiverNews.setSortOrder(maxSortOrder + 1);
            riverNewsService.updateRiverNews(targetRiverNews);
        }
        
        int currentSortOrder = targetRiverNews.getSortOrder();
        
        // 查找排序值刚好小于当前记录的记录
        RiverNews previousRiverNews = riverNewsService.selectPreviousRiverNews(currentSortOrder);
        
        if (previousRiverNews == null) {
            return AjaxResult.error("已经是第一个了");
        }
        
        // 交换排序值
        Integer tempSortOrder = targetRiverNews.getSortOrder();
        targetRiverNews.setSortOrder(previousRiverNews.getSortOrder());
        previousRiverNews.setSortOrder(tempSortOrder);
        
        // 更新数据库
        riverNewsService.updateRiverNews(targetRiverNews);
        riverNewsService.updateRiverNews(previousRiverNews);
        
        return success("上移成功");
    }
    
    /**
     * 将指定记录下移一位
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "河道要闻", businessType = BusinessType.UPDATE)
    @PutMapping("/moveDown/{newsId}")
    public AjaxResult moveDown(@PathVariable Long newsId) {
        // 获取记录
        RiverNews targetRiverNews = riverNewsService.selectRiverNewsByNewsId(newsId);
        
        if (targetRiverNews == null) {
            return AjaxResult.error("记录不存在");
        }
        
        // 如果sortOrder为null，初始化为最大值+1
        if (targetRiverNews.getSortOrder() == null) {
            int maxSortOrder = riverNewsService.selectMaxSortOrder();
            targetRiverNews.setSortOrder(maxSortOrder + 1);
            riverNewsService.updateRiverNews(targetRiverNews);
        }
        
        int currentSortOrder = targetRiverNews.getSortOrder();
        
        // 查找排序值刚好大于当前记录的记录
        RiverNews nextRiverNews = riverNewsService.selectNextRiverNews(currentSortOrder);
        
        if (nextRiverNews == null) {
            return AjaxResult.error("已经是最后一个了");
        }
        
        // 交换排序值
        Integer tempSortOrder = targetRiverNews.getSortOrder();
        targetRiverNews.setSortOrder(nextRiverNews.getSortOrder());
        nextRiverNews.setSortOrder(tempSortOrder);
        
        // 更新数据库
        riverNewsService.updateRiverNews(targetRiverNews);
        riverNewsService.updateRiverNews(nextRiverNews);
        
        return success("下移成功");
    }
    
    /**
     * 初始化现有数据的排序值
     */
    @PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "河道要闻", businessType = BusinessType.UPDATE)
    @PutMapping("/initSortOrder")
    public AjaxResult initSortOrder() {
        try {
            // 获取所有sortOrder为null的记录
            List<RiverNews> nullSortOrderList = riverNewsService.list(
                new QueryWrapper<RiverNews>().isNull("sort_order")
            );
            
            if (nullSortOrderList.isEmpty()) {
                return success("没有需要初始化的数据");
            }
            
            // 获取当前最大排序值
            int maxSortOrder = riverNewsService.selectMaxSortOrder();
            
            // 为每条记录设置排序值
            for (int i = 0; i < nullSortOrderList.size(); i++) {
                RiverNews riverNews = nullSortOrderList.get(i);
                riverNews.setSortOrder(maxSortOrder + i + 1);
                riverNewsService.updateRiverNews(riverNews);
            }
            
            return success("成功初始化 " + nullSortOrderList.size() + " 条记录的排序值");
        } catch (Exception e) {
            return AjaxResult.error("初始化失败: " + e.getMessage());
        }
    }
}
